package manage.util;

import api.model.ApiColumn;
import api.model.ApiTable;
import m.common.model.DictionaryModel;
import m.common.model.FieldMeta;
import m.common.model.Model;
import m.common.model.config.ModelConfig;
import m.html.element.other.DisplayItem;
import m.system.cache.CacheUtil;
import m.system.db.DBManager;
import m.system.util.*;
import manage.model.DictionaryData;

import java.sql.SQLException;
import java.util.*;

public class DictionaryUtil {
	/**
	 * value 是否包含 dict字典中
	 *  value
	 *  dict
	 * 
	 */
	public static boolean isValid(String value,String dict){
		return null!=get(dict).get(value);
	}
	public static boolean isDictType(String dictType) throws SQLException {
		return null != DBManager.queryFirstRow("select oid from os_dictionary_type where type=?", dictType);
	}
	//----------------dictType   dataValue   dataName
	protected static Map<String,Map<String,String>> map= new HashMap<>();
	protected static Map<String,Map<String,String>> titleMap= new HashMap<>();
	protected static Map<String,String[]> valuesMap= new HashMap<>();
	protected final static Map<String,Set<String>> linkTypeMap=new HashMap<>();
	private static void addLinkType(String pt,String st){
		Set<String> set=linkTypeMap.get(pt);
		if(null==set){
			linkTypeMap.put(pt,new HashSet<>());
			set=linkTypeMap.get(pt);
		}
		set.add(st);
	}
	/**
	 * 初始化字典
	 * 普通字典:填字典类型
	 * 类属性:格式填(类全名!属性)
	 * 类缓存列表:格式填(类全名:参数)或者(类全名) 参数根据缓存列表定义设置
	 */
	protected static Map<String,String> init(String dictType){
		if(null==map.get(dictType)){
			synchronized (DictionaryUtil.class) {
				if(null==map.get(dictType)) {
					Map<String,String> dmap = new LinkedHashMap<>();
					Map<String,String> tmap = new LinkedHashMap<>();
					List<String> vlist=new ArrayList<>();
					try {
						if (isDictType(dictType)) {
							List<DictionaryData> dlist = CacheUtil.getList(DictionaryData.class, dictType);//获取缓存
							for (DictionaryData dd : dlist) {
								dmap.put(dd.getValue(), dd.getName() + "|" + (dd.getStatus().equals("0") ? "Y" : "N")+ "|"+StringUtil.noSpace(dd.getParentData().getValue()));
								tmap.put(dd.getValue(), dd.getName());
								vlist.add(dd.getValue());
							}
						} else if (dictType.indexOf("!") > 0) {
							String[] arr = dictType.split("!");
							ApiTable table=CacheUtil.get(ApiTable.class,arr[0]);
							String dt,dp;
							if(null==table) {
								Model mc = ClassUtil.newInstance(arr[0]);
								FieldMeta fm = ModelConfig.getFieldMetaMap(mc.getClass()).get(arr[1]);
								dt=fm.dictType();
								dp=fm.dictOption();
							}else{
								ApiColumn col=CacheUtil.get(ApiColumn.class,table.getOid(),arr[1]);
								dt=col.getDictType();
								dp=col.getDictOption();
							}
							if (!StringUtil.isSpace(dt)) {
								dmap = init(dt);
								tmap = titleMap.get(dt);
								vlist = Arrays.asList(valuesMap.get(dt));
								if (dt.indexOf("!") > 0) {
									addLinkType(dt.split("!")[0], dictType);
								} else {
									addLinkType(dt.split(":")[0], dictType);
								}
							} else if (!StringUtil.isSpace(dp)) {
								String[] opts = dp.split(",");
								for (String str : opts) {
									if (StringUtil.noSpace(str).indexOf(":") > 0) {
										String[] tmp = str.split(":");
										dmap.put(tmp[0], tmp[1] + "|Y|");
										tmap.put(tmp[0], tmp[1]);
										vlist.add(tmp[0]);
									}
								}
							}
						} else {
							String[] arr = dictType.split(":");
							DictionaryModel dict = ClassUtil.newInstance(arr[0]);
							List<DictionaryModel> dlist = dict.getCacheList(arr.length > 1 ? arr[1] : "");
							for (DictionaryModel dd : dlist) {
								dmap.put(dd.getDictValue(), dd.getDictName() + "|" + dd.getDictStatus()+ "|"+dd.getDictParentOid());
								tmap.put(dd.getDictValue(), dd.getDictName());
								vlist.add(dd.getDictValue());
							}
						}
					} catch (Exception e) {
						SystemUtil.printlnIf(true,"字典初始化错误",e.getMessage());
						e.printStackTrace();
					}
					map.put(dictType, dmap);
					titleMap.put(dictType, tmap);
					valuesMap.put(dictType,vlist.toArray(new String[0]));
					SystemUtil.printlnIf(true,"初始化字典",dictType);
				}
			}
		}
		return map.get(dictType);
	}
	/**
	 * 清除全部
	 */
	public static void clearAll(){
		clearAll(true);
	}
	/**
	 * 清除全部  缓存同步执行
	 */
	public static void clearAll(boolean synch){
		if(synch) CacheUtil.clear(DictionaryData.class);
		map= new HashMap<>();
		titleMap= new HashMap<>();
		valuesMap=new HashMap<>();
	}
	/**
	 * 清除
	 *  dictType
	 */
	public static void clear(String dictType){
		clear(dictType,true);
	}

	/**
	 * 清除 字典类
	 */
	public static void clear(Class<? extends DictionaryModel> clazz,String key){
		clear(clazz.getName()+":"+key);
	}
	/**
	 * 清除 缓存同步执行
	 */
	public static void clear(String dictType,boolean synch){
		try {
			if (isDictType(dictType) || dictType.indexOf("!") > 0) {
				if(synch) CacheUtil.clear(DictionaryData.class,dictType);
				map.put(dictType,null);
				titleMap.put(dictType,null);
				valuesMap.put(dictType,null);
			}else{
				String[] arr=dictType.split(":");
				clearLinkType(arr[0]);
				if(synch) CacheUtil.clear(DictionaryData.class,arr[0]);
				for(String k : map.keySet()){
					if(k.indexOf(arr[0])==0){
						map.put(k,null);
						titleMap.put(k,null);
						valuesMap.put(k,null);
					}
				}
			}
			SystemUtil.printlnIf(true,"清除字典",dictType);
		} catch (SQLException e) {
			SystemUtil.printlnIf(true,"清除字典失败",dictType,e.getMessage());
		}
	}
	private static void clearLinkType(String dictClass){
		if(null!=linkTypeMap.get(dictClass)) {
			for (String k : linkTypeMap.get(dictClass)) {
				clear(k);
			}
		}
	}
	/**
	 * 清除
	 */
	public static <T extends DictionaryModel> void clear(Class<T> clazz){
		clear(clazz.getName());
	}
	/**
	 * 获取字典名称
	 *  dictType 字典类型
	 *  dataValue 字典值
	 * 
	 */
	public static String getName(String dictType,String dataValue){
		if(null==dataValue){
			return "";
		}else{
			return getName(dictType,dataValue.split(","));
		}
	}
	public static String getName(String dictType,Object dataValue){
		if(null==dataValue){
			return "";
		}else if(dataValue.getClass().isArray()) {
			return getName(dictType, (String[])dataValue);
		}else{
			return getName(dictType, dataValue.toString());
		}
	}
	public static String getName(String dictType,String[] arr){
		init(dictType);
		Map<String,String> map=titleMap.get(dictType);
		List<String> list= new ArrayList<>();
		for(String s : arr){
			String v=map.get(s);
			list.add(null==v?s:v);
		}
		if(!list.isEmpty()){
			return ArrayUtil.connection(list.toArray(new String[]{}), ",");
		}else{
			return "";
		}
	}
	/**
	 * 获取对应字典下的所有字典值.
	 */
	public static Map<String,String> get(String dictType){
		init(dictType);
		return map.get(dictType);
	}
	/**
	 * 获取对应字典下的所有字典值. 不含状态和父节点
	 */
	public static Map<String,String> getTitle(String dictType){
		init(dictType);
		return titleMap.get(dictType);
	}

	/**
	 * 通过字典显示值，获取字典value
	 */
	public static String getValue(String dictType,String name){
		init(dictType);
		Map<String,String> map=getTitle(dictType);
		for(String key : map.keySet()){
			if(map.get(key).equals(name)){
				return key;
			}
		}
		return null;
	}

	/**
	 * 获取字典对应的所有value值，包含禁用的，可用于检测输入项
	 */
	public static String[] getValues(String dictType){
		init(dictType);
		return valuesMap.get(dictType);
	}
	public static JSONMessage toDictData(List<DisplayItem> items){
		Map<String,String> map=new HashMap<>();
		for(DisplayItem item :items){
			map.put(item.getValue(),item.getTitle()+"|Y|"+item.getParentValue());
		}
		return new JSONMessage(0).push("map",map);
	}
}
